<?php

namespace App\Admin\Controllers;

use App\Coupon;
use App\CouponJob;

use App\Jobs\CouponSendJob;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\MessageBag;

class CouponJobController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('优惠券发送全部人员');
            $content->description('优惠券发送全部人员');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('优惠券发送全部人员');
            $content->description('优惠券发送全部人员');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('优惠券发送全部人员');
            $content->description('优惠券发送全部人员');
            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(CouponJob::class, function (Grid $grid) {

            $grid->id('ID')->sortable();
            $grid->type('类型')->display(
                function($value){
                    return CouponJob::$typeMap[$value];
                }
            );
            $grid->coupon_id('优惠券')->display(function ($value){
                return Coupon::find($value)->name;
            });
            $grid->status('发送状态')->display(function($value){
                return $value==0 ? '发送中' : '已完成';
            });
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableActions();
            $grid->created_at('发送时间');

        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(CouponJob::class, function (Form $form) {
          //  $form->display('type','全体人员');
            $form->select('coupon_id','优惠券')->options(Coupon::getSelectOptions());
            $form->saved(function ($form) {
                $id=$form->model()->id;
                $couponJob= CouponJob::find($id);
                dispatch(new CouponSendJob($couponJob));
                $success = new MessageBag([
                    'title'   => '保存成功',
                    'message' => '优惠券发送中',
                ]);


                return back()->with(compact('success'));
            });
        });
    }
}
